

<template>
  <div>
    <h1>MQTT Web Demo</h1>
    <div>
      <input v-model="topic" placeholder="Enter Topic" />
      <button @click="handleSubscribe">Subscribe</button>
      <button @click="handleUnsubscribe">Unsubscribe</button>
    </div>
    <div>
      <input v-model="publishTopic" placeholder="Enter Publish Topic" />
      <input v-model="publishMessage" placeholder="Enter Message" />
      <button @click="handlePublish">Publish</button>
    </div>
    <div>
      <h2>Received Messages:</h2>
      <ul>
        <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
      </ul>
    </div>
  </div>
</template>


<script setup>
import {onBeforeUnmount, ref} from "vue";
import mqttClient from "../utils/mqtt";
import {getCookie} from "~/api/manager.js";

// 数据
const topic = ref(""); // 订阅的 Topic
const publishTopic = ref(""); // 发布的 Topic
const publishMessage = ref(""); // 发布的消息
const messages = ref([]); // 接收到的消息

// 订阅 Topic
const handleSubscribe = () => {
  if (topic.value) {
    mqttClient.subscribe(topic.value, (message) => {
      messages.value.push(message);
    });
  } else {
    alert("Please enter a topic");
  }
};

// 取消订阅
const handleUnsubscribe = () => {
  if (topic.value) {
    mqttClient.unsubscribe(topic.value);
  } else {
    alert("Please enter a topic");
  }
};

// 发布消息
const handlePublish = () => {
  if (publishTopic.value && publishMessage.value) {
    mqttClient.publish(publishTopic.value, publishMessage.value);
  } else {
    alert("Please enter a topic and message");
  }
};
const token = getCookie('yuan-token');
// 组件挂载时连接 MQTT Broker
mqttClient.connect("ws://yuanying.top:8083/mqtt",{
  username:"",
  password: token,
  clientId: '123', // 随机生成 clientId
});

// 组件卸载时断开连接
onBeforeUnmount(() => {
  mqttClient.disconnect();
});
</script>

<style scoped>
div {
  margin: 10px;
}
button {
  margin-left: 10px;
}
</style>